/**
 * Created by zhaojiuyang1 on 15/4/15.
 */
var Q = require('q');
var _ = require('underscore');
var express = require('express');
var app = express();
var moment = require('moment');

var handlerIndex = require(__dirname+'/lib/index.js');
var handlers = handlerIndex.handlers;

var init = function(){
    handlerIndex.initOptions()
        .then(applyRoute)
        .then(function(){
            console.log('服务器初始化成功，监听端口80');
        },function(err){
            console.err('服务器 初始化错误');
        });
};
app.use(function(req, res, next){
    console.log(req.path);
    next();
});

var applyRoute = function(){
    var routes = require(__dirname+'/config/route.js').routes;
    for(var path in routes){
        function execute(){
            var request = routes[path].request;
            var action = routes[path].action;
            var method = routes[path].method;
            console.log("正在注册路径:"+path);
            console.log("正在注册action:"+action);
            console.log("正在注册路径方法:"+method);
            console.log("正在注册路径请求方式:"+request);
            if(request === 'get,post'){
                app.get(path,function(req,res){
                    console.log(req.path);
                    console.log('handlers.'+action+'.'+method+'(req,res)');
                    eval('handlers.'+action+'.'+method+'(req,res)');
                    console.log(req.path);
                });
                app.post(path,function(req,res){
                    console.log(req.path);
                    console.log('handlers.'+action+'.'+method+'(req,res)');
                    eval('handlers.'+action+'.'+method+'(req,res)');
                    console.log(req.path);
                })
            }else if(request === 'get'){
                app.get(path,function(req,res){
                    console.log(req.path);
                    console.log('handlers.'+action+'.'+method+'(req,res)');
                    eval('handlers.'+action+'.'+method+'(req,res)');
                    console.log(req.path);
                });
            }else{
                app.post(path,function(req,res){
                    console.log('handlers.'+action+'.'+method+'(req,res)');
                    eval('handlers.'+action+'.'+method+'(req,res)');
                    console.log(req.path);
                })
            }
        }
        execute();
    }
};
init();
app.listen(8766);
